<template>
  <div class="shop-cart">
    <van-nav-bar title="购物车" left-arrow @click-left="$router.back()" />
    <van-empty
      v-if="cartList.length === 0"
      description="购物车为空"
      image="https://img.yzcdn.cn/vant/custom-empty-image.png"
    />
    <div v-else>
      <van-list>
        <van-card
          v-for="item in cartList"
          :key="item.id"
          :num="item.quantity"
          :price="item.price"
          :desc="item.description"
          :title="item.name"
          :thumb="item.image"
          class="goods-card"
        >
          <template #footer>
            <van-stepper v-model="item.quantity" @change="updateQuantity(item)" />
          </template>
        </van-card>
      </van-list>
      <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="submitOrder" />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { Toast } from 'vant'
import axios from 'axios'

export default {
  name: 'ShopCart',
  setup() {
    const cartList = ref([]) // 购物车列表
    const token = 'your_token_here' // 替换为你的 token

    // 获取购物车数据
    const fetchCartData = async () => {
      try {
        const response = await axios.get('http://localhost:1337/api/v1/shop_carts', {
          headers: { token }, // 设置请求头，携带 token
        })
        if (response.data.code === 1) {
          cartList.value = response.data.data || [] // 将数据赋值给 cartList
        } else {
          Toast.fail('获取购物车数据失败：' + response.data.message) // 提示失败信息
        }
      } catch (error) {
        console.error('请求失败:', error)
        Toast.fail('网络错误，请稍后再试') // 提示网络错误
      }
    }

    // 更新商品数量
    const updateQuantity = async (item) => {
      try {
        const response = await axios.post(
          'http://localhost:1337/api/v1/shop_carts/update',
          {
            id: item.id,
            quantity: item.quantity,
          },
          {
            headers: { token }, // 设置请求头，携带 token
          },
        )
        if (response.data.code === 1) {
          Toast.success('更新成功')
        } else {
          Toast.fail('更新失败：' + response.data.message)
        }
      } catch (error) {
        console.error('请求失败:', error)
        Toast.fail('网络错误，请稍后再试')
      }
    }

    // 提交订单
    const submitOrder = () => {
      if (cartList.value.length === 0) {
        Toast.fail('购物车为空')
        return
      }
      Toast('提交订单功能暂未实现')
    }

    // 计算总价
    const totalPrice = computed(() => {
      return cartList.value.reduce((total, item) => total + item.price * item.quantity, 0) * 100
    })

    // 在页面加载时获取购物车数据
    onMounted(fetchCartData)

    return {
      cartList,
      updateQuantity,
      submitOrder,
      totalPrice,
    }
  },
}
</script>

<style scoped>
.goods-card {
  margin-bottom: 10px;
}
</style>
